package cn.itcast.service.system.impl;

import cn.itcast.dao.system.UserDao;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public List<User> findAll(String companyId) {
        return userDao.findAll(companyId);
    }

    @Override
    public User findById(String id) {
        return userDao.findById(id);
    }

    @Override
    public void save(User user) {
        String OPassword = user.getPassword();
        String password = new Md5Hash(OPassword,user.getEmail(),2).toString();
        user.setPassword(password);
        userDao.save(user);

        Map<String,String> map = new HashMap<>();
        map.put("email",user.getEmail());
        map.put("subject","【SaaS货代云平台】注册成功");
        map.put("content","欢迎加入SaaS货代云平台，您可以通过邮箱登录，密码是："+OPassword);
        amqpTemplate.convertAndSend("email.send",map);
    }

    @Override
    public void updateById(User user) {
        userDao.updateById(user);
    }

    @Override
    public void deleteById(String id) {
        userDao.deleteById(id);
    }

    @Override
    public PageInfo<User> findByPage(Integer page, Integer pageSize, String companyId) {
        PageHelper.startPage(page, pageSize);
        List<User> list = userDao.findAll(companyId);
        return new PageInfo<>(list, 5);
    }

    @Override
    public void saveUserAndRole(String userid, String[] roleIds) {
        userDao.deleteRoleAndUserByUserId(userid);
        for (String roleId : roleIds) {
            userDao.saveUserAndRole(userid, roleId);
        }
    }

    @Override
    public void deleteRoleAndUserByUserId(String id) {
        userDao.deleteRoleAndUserByUserId(id);
    }

    @Override
    public User findByEmail(String email) {
        User user = userDao.findByEmail(email);
        return user;
    }
}
